package org.netease.im;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.HttpPost;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Date;

/**
 * @author Firrela
 * @time 2016/3/7.
 */
public class NIMPost {

    private static Logger logger = LoggerFactory.getLogger(NIMPost.class);

   
    public static String postNIMServer(String url, final HttpEntity entity, String appKey, String appSecret, Boolean requestJson)
            throws IOException {
        HttpClientUtil httpClientUtil = new HttpClientUtil();
        HttpPost post = httpClientUtil.createPost(url, entity, null);

        // addHeader
        HttpClientUtil.addHeader(post, "AppKey", appKey);
        String nonce = UUIDUtil.getUUID();
        //时间必须和网易服务器同步，否则会报错
        String curTime = String.valueOf((new Date()).getTime() / 1000L); //  String curTime = String.valueOf(System.currentTimeMillis() / 1000);
        //logger.info("curTime {}", curTime);
        HttpClientUtil.addHeader(post, "Nonce", nonce);
        HttpClientUtil.addHeader(post, "CurTime", curTime);
        String checksum = getCheckSum(nonce, curTime, appSecret);
        HttpClientUtil.addHeader(post, "CheckSum", checksum);

        if(requestJson) {
            HttpClientUtil.addHeader(post, "Content-Type", "application/json;charset=utf-8");
        }

        // logger
        //logger.info("Nonce {} | CurlTime {} | CheckSum {}", new Object[]{nonce, curTime, checksum});

        String stringResult = httpClientUtil.fetchData(post);
        //return result;
        //logger.info("StringBody {}", stringResult);

        return stringResult;
    }
    private static String getCheckSum(String nonce, String curTime, String appSecret) {
        //String plaintext = new StringBuffer(appSecret).append(nonce).append(curTime).toString();
        //logger.info("checkSum {}", EncodeUtil.encode(plaintext, "SHA1"));
        //return EncodeUtil.encode(plaintext, "SHA1");

        return CheckSumBuilder.getCheckSum(appSecret, nonce, curTime);
    }
}
